package fun.eliauk.shuatiba.manager;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.IntegerCodec;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CounterManager {
    @Resource
    private RedissonClient redisson;


     /**
     * 增加计数 并返回计数
     *
     * @param key                     缓存键
     * @param timeInterval            时间间隔
     * @param timeUnit                时间间隔单位
     * @param expirationTimeInSeconds 键值过期时间 （单位秒）
     * @return
     */
    public long incrAndGetCounter(String key, int timeInterval, TimeUnit timeUnit, int expirationTimeInSeconds) {
        if (StrUtil.isBlank(key)) {
            return 0;
        }

        if (timeInterval <= 0) {
            throw new IllegalArgumentException("时间间隔必须大于零。");
        }
        long timeFactor;
        switch (timeUnit) {
            case SECONDS:
                timeFactor = Instant.now().getEpochSecond() / timeInterval; //Instant.now().getEpochSecond() 在 1s 内计算的值始终是一样的
                break;
            case MINUTES:
                timeFactor = Instant.now().getEpochSecond() / timeInterval / 60; // 在 1 分钟内计算的值始终是一样的
                break;
            case HOURS:
                timeFactor = Instant.now().getEpochSecond() / timeInterval / 60 / 60; // 在 1小内计算的值始终是一样的
                break;
            default:
                throw new IllegalArgumentException("不支持的时间单位: " + timeUnit);
        }

        String redisKey = key + ":" + timeFactor;

        // Lua 脚本
        String luaScript = "if redis.call('exists', KEYS[1]) == 1 then " +
                "  return redis.call('incr', KEYS[1]); " +
                "else " +
                "  redis.call('set', KEYS[1], 1); " +
                "  redis.call('expire', KEYS[1], ARGV[1]); " +
                "  return 1; " +
                "end";

        // 执行 Lua 脚本
        RScript script = redisson.getScript(IntegerCodec.INSTANCE);
        Object countObj = script.eval(
                RScript.Mode.READ_WRITE,
                luaScript,
                RScript.ReturnType.INTEGER,
                Collections.singletonList(redisKey), expirationTimeInSeconds);
        return (long) countObj;
    }


    /**
     * 增加并返回计数
     *
     * @param key          缓存键 键值过期的时间是 时间单位 * 时间间隔单位
     * @param timeInterval 时间间隔
     * @param timeUnit     时间间隔单位
     * @return
     */
    public long incrAndGetCounter(String key, int timeInterval, TimeUnit timeUnit) {
        int expirationTimeInSeconds;
        switch (timeUnit) {
            case SECONDS:
                expirationTimeInSeconds = timeInterval;
                break;
            case MINUTES:
                expirationTimeInSeconds = timeInterval * 60;
                break;
            case HOURS:
                expirationTimeInSeconds = timeInterval * 60 * 60;
                break;
            default:
                throw new IllegalArgumentException("Unsupported TimeUnit. Use SECONDS, MINUTES, or HOURS.");
        }

        return incrAndGetCounter(key, timeInterval, timeUnit, expirationTimeInSeconds);
    }

    /**
     * 增加并返回计数，默认统计一分钟内的计数结果
     *
     * @param key 缓存键
     * @return
     */
    public long incrAndGetCounter(String key) {
        return incrAndGetCounter(key, 1, TimeUnit.MINUTES);
    }

}
